package cn.com.dbappsecurity.task;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.io.IOUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import cn.com.dbappsecurity.utils.MybatisUtil;

public class InitDbTask {

	private static final Logger LOG = Logger.getLogger(InitDbTask.class);
	
	/**
	 * 数据库表不存在,则创建
	 * @throws SQLException 
	 * @throws Exception 
	 */
	public void execute() throws Exception{
		if(!dbIsEmpty()){
			LOG.debug("数据库存在表，不再创建");
			return;
		}
		SqlSession session = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		BufferedReader br = null;
		InputStream is = null;
		InputStreamReader isr = null;
		try {
			session = MybatisUtil.sqlSessionFactory.openSession(true);
			Connection con = session.getConnection();
			is = this.getClass().getResourceAsStream("/init.sql");
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			String line;
			StringBuffer sql = new StringBuffer();
			while((line = br.readLine()) != null){
				line = line.trim();
				sql.append(line);
				if(line.endsWith(";")){
					con.createStatement().execute(sql.toString());
					sql.delete(0,sql.length());
				}else{
					sql.append(' ');
				}
			}
		}finally{
			IOUtils.closeQuietly(br);
			IOUtils.closeQuietly(isr);
			IOUtils.closeQuietly(is);
			closeResultSet(rs);
			closePreparedStatement(ps);
			if(session != null){
				session.close();
			}
		}
	}
	
	/*
	 * 判断数据库是否为空
	 * @return
	 * @throws SQLException
	 */
	private boolean dbIsEmpty() throws SQLException{
		SqlSession session = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			session = MybatisUtil.sqlSessionFactory.openSession(true);
			Connection con = session.getConnection();
			ps = con.prepareStatement("show tables");
			rs = ps.executeQuery();
			if(rs.next()){
				return false;
			}
		}finally{
			closeResultSet(rs);
			closePreparedStatement(ps);
			if(session != null){
				session.close();
			}
		}
		return true;
	}
	
	private static void closeResultSet(ResultSet rs){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				LOG.error("关闭rs出错",e);
			}
		}
	}
	
	private static void closePreparedStatement(PreparedStatement ps){
		if(ps != null){
			try {
				ps.close();
			} catch (SQLException e) {
				LOG.error("关闭ps出错",e);
			}
		}
	}
	
}
